package com.example.administrator.text;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import util.BReceiverUtil.SMSBroadcastReceiver;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetUtils;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import view.diaLogView.CrowdRetunDialog;
import view.diaLogView.PhoneMessageDialog;
import view.diaLogView.UploadDialog;

/**
 * 修改信息页
 */
public class ModifyInformation1Activity extends BaseActivity {
    private String mType,mToken,mID,mUrl,mValue;
    private String mStringPhone,mStringPassword;
    private String mStringContent;
    public boolean mJuderMessage = true;
    private boolean mModif_nan,mModif_nV = true;
    private UploadDialog mUploadDialog;
    private SMSBroadcastReceiver mSmsBroadcastReceiver;

    @Bind(R.id.modifypassword1_frame)         FrameLayout mFrameLayout;
    @Bind(R.id.activity_weinformation1_cv1)   CardView mCardView1;
    @Bind(R.id.activity_weinformation1_cv2)   CardView mCardView2;
    @Bind(R.id.linear_modif1_sex)             LinearLayout mLayoutSex;
    @Bind(R.id.edittext_weinformation1)       EditText mEditText;
    @Bind(R.id.text_modify_name1)             TextView mTextView;
    @Bind(R.id.text_modify1_verification)     TextView mTVVerification;
    @Bind(R.id.edit_modify1_phone)            EditText mETPhone;
    @Bind(R.id.edit_modify1_verification)     EditText mETVerification;
    @Bind(R.id.checkbox_modify1_nan)          AppCompatCheckBox mBoxNan;
    @Bind(R.id.checkbox_modify1_nv)           AppCompatCheckBox mBoxNv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modifypassword1);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        mType = getIntent().getStringExtra("type");
        HomeUtil.getHemeUtilNew().getStatusBar(this,mFrameLayout);
        mToken = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mTokenDB,"");
        mID = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mUseridDB,"");
        if(mType.equals(ModifyInformationActivity.PWD)){
            mTextView.setText("设置密码");
            mCardView1.setVisibility(View.VISIBLE);
            mCardView2.setVisibility(View.GONE);
            mLayoutSex.setVisibility(View.GONE);
            mEditText.setHint("请输入您要修改的密码(6到12位的数字或字母)");
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }else if(mType.equals(ModifyInformationActivity.NICKNAME)){
            mTextView.setText("设置昵称");
            mCardView1.setVisibility(View.VISIBLE);
            mCardView2.setVisibility(View.GONE);
            mLayoutSex.setVisibility(View.GONE);
            mEditText.setHint("请输入您要修改的昵称");
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }else if(mType.equals(ModifyInformationActivity.PHONE)){
            mTextView.setText("重置手机号");
            mCardView1.setVisibility(View.GONE);
            mCardView2.setVisibility(View.VISIBLE);
            mLayoutSex.setVisibility(View.GONE);
        }else if(mType.equals(ModifyInformationActivity.SEX)){
            mTextView.setText("设置性别");
            mCardView1.setVisibility(View.GONE);
            mCardView2.setVisibility(View.GONE);
            mLayoutSex.setVisibility(View.VISIBLE);
            int sex = (int)SharedPreferencesUtils.getParam(this,ModifyInformationActivity.SEX,1);
            if(sex == 1){
                mBoxNan.setChecked(true);
            }else if(sex == 2){
                mBoxNv.setChecked(true);
            }
        }

        mETPhone.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    mTVVerification.setTextColor(getResources().getColor(R.color.Land_true));
                    mStringPhone = s.toString();
                } else if (s.length() <11) {
                    mStringPhone = s.toString();
                    mTVVerification.setTextColor(getResources().getColor(R.color.Land_false));
                }
            }

            @Override public void afterTextChanged(Editable s) {

            }
        });

    }

    /**
     * 返回
     */
    @OnClick(R.id.image_modifypassword1)
    void Return(){
        finish();
    }

    /**
     * 完成   13501574099
     */
    @OnClick(R.id.text_modifypassword1)
    void ok(){
        if(!mType.equals(ModifyInformationActivity.PHONE)){
            mStringContent = mEditText.getText().toString().trim();
            HashMap<String,Object> hashMap = new HashMap<>();
            hashMap.put("userid",mID);
            hashMap.put("type",mType);

            if(mType.equals(ModifyInformationActivity.SEX)){
                if(mBoxNan.isChecked()){
                    mStringContent = "1";
                }
                if(mBoxNv.isChecked()){
                    mStringContent = "2";
                }
                if(mStringContent.equals("")){
                    getToast("请选择性别");
                    return;
                }
            }

            if(mType.equals(ModifyInformationActivity.PWD)){
                if(StringUtil.getStringUtilNew().getStatePassword(mStringContent)){
                    mStringContent = StringUtil.getStringUtilNew().getMD5String(mStringContent);
                }else {
                    getToast("请输入符合规定的密码");
                    return;
                }
            }

            if(mStringContent.equals("")){
                getToast("修改的内容不能为空");
                return;
            }

            hashMap.put("content",mStringContent);
            String stringJson = StringUtil.getStringUtilNew().hashMapToJson(hashMap);
            long time = StringUtil.getStringUtilNew().getTimeCurrent();
            String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngUserContent_updateContent,stringJson,mToken,mID,time);
            Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mID, Url.mStirngUserContent_updateContent,stirngSign,time);
            if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
                mUrl = Url.getUrlNew().getAppIP();
            }else {
                mUrl = MyApplication.getApp().getFWQString();
            }

            mUploadDialog = new UploadDialog(this,"保存中");
            mUploadDialog.show();
            getLogger().info("ok()--->修改个人信息--fwq"+mUrl+"stirngSign--"+stringJson);
            GreenTreeNetworkUtil.getInstance().doPost(this,mUrl,1,map,new RequestDataCallback() {
                @Override public void onSuccess(String response) {
                    try {
                        getLogger().info("ok()--->onSuccess()--String"+response);
                        JSONObject jsonObject = new JSONObject(response);
                        LogUtil.eE("",response);
                        mUploadDialog.dismiss();
                        if (jsonObject.getInt("code") == 1) {
                            setInformation(mStringContent);
                            Toast.makeText(ModifyInformation1Activity.this,"修改成功",Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.putExtra("type",mType);
                            intent.putExtra("content",mStringContent);
                            setResult(RESULT_OK, intent);
                            finish();
                        } else if(jsonObject.getInt("code") == -2){
                            CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(ModifyInformation1Activity.this);
                            crowdRetunDialog.show();
                        }
                        else {getToast(getString(R.string.FWQ));}

                    } catch (JSONException e) {e.printStackTrace();}
                }

                @Override public void onFailure(Throwable error) {
                    Toast.makeText(ModifyInformation1Activity.this,"修改失败",Toast.LENGTH_SHORT).show();
                    mUploadDialog.dismiss();
                    StringUtil.getStringUtilNew().getExceptionCode(ModifyInformation1Activity.this,error.toString());
                }});
        }else {
            setPhone();
        }
    }

    /**
     * 验证码
     */
    @OnClick(R.id.text_modify1_verification)
    void modifyVerification(){

        if (StringUtil.getStringUtilNew().isMobile(mStringPhone)) {
            if (NetUtils.getInstance(this).checkNetWork()) {
                if (mJuderMessage) {
                    HomeUtil.getHemeUtilNew().getMessage(this,mETVerification,mSmsBroadcastReceiver);
                    mMap = new HashMap<>();
                    mMap.put("phone", mStringPhone);
                    mMap.put("authCodeType",0);
                    String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
                    long time = StringUtil.getStringUtilNew().getTimeCurrent();
                    String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngPhoneVerification,stringJson,"null","0",time);
                    Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,"null","0", Url.mStirngPhoneVerification,stirngSign,time);
                    HomeUtil.getHemeUtilNew().obtainVerification(this,map1, MyApplication.getApp().getFWQString(),mTVVerification, 0,1);
                    mJuderMessage = false;
                } else {
                    PhoneMessageDialog phoneMessageDialog = new PhoneMessageDialog(this,mStringPhone, MyApplication.getApp().getFWQString(),mETVerification, mTVVerification);
                    phoneMessageDialog.show();
                }
            } else {
                super.getToast(getString(R.string.no_network));
            }
        } else {
            super.getToast(getString(R.string.no_phone));
        }
    }

    /**
     * 设置手机号
     */
    private void setPhone() {
        final String phone = mETPhone.getText().toString().trim();
        final String verification = mETVerification.getText().toString().trim();
        if(getEntryObtain()){
            HashMap<String,Object> hashMap = new HashMap<>();
            hashMap.put("userid",mID);
            hashMap.put("phone",phone);
            hashMap.put("authcode",verification);
            String stringJson = StringUtil.getStringUtilNew().hashMapToJson(hashMap);
            long time = StringUtil.getStringUtilNew().getTimeCurrent();
            String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngUserContent_updatePhone,stringJson,mToken,mID,time);
            Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mID, Url.mStirngUserContent_updatePhone,stirngSign,time);
            if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
                mUrl = Url.getUrlNew().getAppIP();
            }else {
                mUrl = MyApplication.getApp().getFWQString();
            }
            getLogger().info("setPhone()--->修改手机号码--fwq"+mUrl+"stirngSign--"+stirngSign);
            GreenTreeNetworkUtil.getInstance().doPost(this,mUrl,1,map,new RequestDataCallback() {
                @Override public void onSuccess(String response) {
                    try {
                        getLogger().info("setPhone()--->onSuccess--String"+response);
                        JSONObject jsonObject = new JSONObject(response);
                        LogUtil.eE("",response);
                        if (jsonObject.getInt("code") == 1) {
                            Intent intent = new Intent();
                            intent.putExtra("type",mType);
                            intent.putExtra("content",phone);
                            setResult(RESULT_OK, intent);
                            finish();
                            Toast.makeText(ModifyInformation1Activity.this,"修改成功",Toast.LENGTH_SHORT).show();
                        } else if(jsonObject.getInt("code") == -2){
                            CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(ModifyInformation1Activity.this);
                            crowdRetunDialog.show();
                        }
                        else {getToast(getString(R.string.FWQ));}

                    } catch (JSONException e) {e.printStackTrace();}
                }

                @Override public void onFailure(Throwable error) {
                    StringUtil.getStringUtilNew().getExceptionCode(ModifyInformation1Activity.this,error.toString());
                }});
        }
    }

    /**
     * 成功后保障在本地
     */
     private void setInformation(String string){
         if(mType.equals(ModifyInformationActivity.PWD)){
             SharedPreferencesUtils.setParam(this, ModifyInformationActivity.PWD,1);
         }else if(mType.equals(ModifyInformationActivity.NICKNAME)){
             SharedPreferencesUtils.setParam(this, ModifyInformationActivity.NICKNAME,string);
         }else if(mType.equals(ModifyInformationActivity.PHONE)){
             SharedPreferencesUtils.setParam(this, ModifyInformationActivity.PHONE,string);
         }else if(mType.equals(ModifyInformationActivity.SEX)){
             if(string.equals("1")){
                 SharedPreferencesUtils.setParam(this,ModifyInformationActivity.SEX,1);
             }else if(string.equals("2")){
                 SharedPreferencesUtils.setParam(this,ModifyInformationActivity.SEX,2);
             }
         }
     }


    /**
     * 获取和验证登录信息
     */
    private boolean getEntryObtain() {

        mStringPhone = mETPhone.getText().toString().trim();
        mStringPassword = mETVerification.getText().toString().trim();

        if (!StringUtil.getStringUtilNew().isMobile(mStringPhone)) {
            super.getToast("手机号不正确");
            return false;
        }
        if (!StringUtil.getStringUtilNew().getStatePassword(mStringPassword)) {
            super.getToast("密码或验证码不正确");
            return false;
        }
        return true;
    }

    /**
     * 男
     */
    @OnClick({R.id.linear_modif1_nan,R.id.checkbox_modify1_nan})
    void modif_nan(){
        if(mModif_nan){
            mModif_nan = false;
            mBoxNan.setChecked(true);
            mBoxNv.setChecked(false);
            mModif_nV = true;

        }else {
            mModif_nan = true;
            mBoxNan.setChecked(false);
        }
    }

    /**
     * 女
     */
    @OnClick({R.id.linear_modif1_nv,R.id.checkbox_modify1_nv})
    void modif_nv(){
        if(mModif_nV){
            mModif_nV = false;
            mBoxNv.setChecked(true);
            mBoxNan.setChecked(false);
            mModif_nan = true;

        }else {
            mModif_nV = true;
            mBoxNv.setChecked(false);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mUploadDialog !=null){
            mUploadDialog.dismiss();
        }
        if(mSmsBroadcastReceiver !=null){
            unregisterReceiver(mSmsBroadcastReceiver);
        }
    }
}
